module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    clean: {
      build: ['build']
    },

    uglify: {
      options: {
        // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: [{
            expand: true,
            cwd: 'public/ted/js',
            src: ['**/*.js'],
            dest: 'build/fe'
        }]
      }      
    },

    concat: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd HH:MM:ss") %> */\n',
        separator: '\n/*=======*/\n'
      },
      dist: {
        src: ['build/fe/**/*.js'],
        dest: 'public/ted/dist/<%= pkg.name %>.js'
      }
    },

    jshint: {
      files: [
        'Gruntfile.js', 
        'routes/*.js', 
        'service/*.js',
        'utils/*.js',
        'public/ted/js/**/*.js'
        ],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true,
          document: true
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-clean');

  grunt.registerTask('distall', ['clean:build','uglify:dist','concat:dist','release']);
  grunt.registerTask('dist', ['clean:build','uglify:dist','concat:dist']);

  grunt.registerTask('default', ['jshint']);


  grunt.registerTask('release', 'release task', function() {
    var fs = require('fs');
    var oldFile = 'public/ted/index.html';
    var newFile = 'public/ted/index.redist.html';
    var content = fs.readFileSync(oldFile,{encoding:'utf-8'});
    var reg = /<!--CATJS-->(\s|\S|.)*?<!--CATJS-->/m;
    var dist = '<!--CATJS-->\n' + 
    '<script src="/ted/dist/ted.js"></script>\n' +
    '<!--CATJS-->\n';
    var newcontent = content.replace(reg,dist);

    fs.writeFileSync(newFile,newcontent,{encoding:'utf-8'});
    fs.renameSync(oldFile, oldFile+'.bak');
    fs.renameSync(newFile, oldFile);
  });

};